package org.example.service02.core;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class MyLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
    private String serviceId;
    private AtomicInteger atomicCount = new AtomicInteger(0);
    private AtomicInteger atomicCurrentindex = new AtomicInteger(0);

    public MyLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) {
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
        this.serviceId = serviceId;
    }


    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier serviceInstanceListSupplier = serviceInstanceListSupplierProvider.getIfAvailable();
        return serviceInstanceListSupplier.get().next().map(this::getInstanceResponse);
    }

    /**
     * 实现每个实例执行两次才会轮询到下一个实例
     * @param instances
     * @return
     */
    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {
        //每个服务都被调用2次
        ServiceInstance instance = null;

        if (instances.isEmpty()) {
            return new EmptyResponse();
        }

        int requestNumber = atomicCount.incrementAndGet();
        if (requestNumber < 2) {
            instance = instances.get(atomicCurrentindex.get());
        } else {
            //大于2时重置
            atomicCount = new AtomicInteger(0);
            //atomicCurrentindex加1
            atomicCurrentindex = new AtomicInteger(atomicCurrentindex.get() + 1);
            if (atomicCurrentindex.get() >= instances.size()) {
                atomicCurrentindex = new AtomicInteger(0);
                instance = instances.get(atomicCurrentindex.get() - 1);
                return new DefaultResponse(instance);
            }

            instance = instances.get(atomicCurrentindex.get() - 1);
        }

        return new DefaultResponse(instance);
    }
}
